/**
 * Created by zzy on 2016/11/13.
 */
var $ = require('jquery');
require('ueditor');
var ZeroClipboard = require('ueditor/third-party/zeroclipboard/ZeroClipboard');
window.ZeroClipboard = ZeroClipboard;
require("./ajaxfileupload.js");
//require("ueditor/ueditor.config");
var $alert = require('libs/alert');
require('layout/util');
require('layout/uiJs');
var $form = require('js-path/formValide.js');
var $form2 = require('js-path/formValideNotSub.js');
require('bootstrap-datetimepicker/locales/bootstrap-datetimepicker.zh-CN');
var news_category={"1":"新闻","2":"服务与帮助","3":"政策法规","4":"系统公告"};
var mapping={"1":{"1":"平台动态","2":"行业动态","3":"永康动态","4":"通知公告"},"2":{"7":"服务中心","8":"常见问题","9":"合作流程","10":"咨询与视频","11":"设备购置","12":"设备人员配置","13":"设备人员要求"},"3":{"5":"政策法规"},"4":{"6":"系统公告"}};
var _ue = UE.getEditor('editor');
var emptyImgPath = $('.imghead').attr('src');
$("#category").on("change",function () {
    typeInit($("#category").val());
});
dataInit();
$(".diyCancel").click(function(){
    $('.imghead').attr("src", emptyImgPath);
    $('#cancel').removeClass('diyCancel');
    $('#top_pic').val("");
});
isPicBlank();
$('.upload').change(function(){
    var objUrl = getObjectURL(this.files[0]) ;

    if (objUrl) {
        $(this).parent().prev('.preview').find('.imghead').attr("src", objUrl) ;
    }
    //当有图片时显示cancel按钮
    isPicBlank();
});
formValidationInit();
function dataInit() {
    var id =$.getUrlParam('id');
    $.ajax({
        url:'api/v1/p/mms/article/load',
        type:'post',
        data:{
            id:id
        },
        dataType:'json',
        success:function (result) {
            if(result.code=="200"){
                var data = result.data;
                categoryInit(data.category);
                typeInit(data.category,data.type+'');
                formInit(data);
            }else{
                $alert(result.message);
            }
        }
    })
}
function formInit(data) {
    $("#id").val(data.id);
    if(data.picturePath==null||data.picturePath==''){
        $('#cancel').removeClass('diyCancel');
        $('#hasPic').val("N");
    }else{
        $("#main_form img").attr("src",data.picturePath);
        $('#cancel').addClass('diyCancel');
        $('#hasPic').val("Y");
    }
    if(data.isHead==1){
        $("#is_head").attr("checked","checked");
    }else{
        $("#is_head").attr("checked",false);
    }
    $("#title").val(data.title);
    $("#url").val(data.url);
    $("#auther").val(data.auther);
    $("#summary").val(data.summary);
    $("#keywords").val(data.keywords);
    $("#stat").empty();
    if(data.stat=="1"){
        $("#stat").append("<span style='color:green'>已发布</span>")
    }else{
        $("#stat").append("<span style='color:red'>未发布</span>")
    }
    if(data.releaseTime){
        var d = new Date(data.releaseTime.replace(/-/g,"/"));
        $('#releaseTime').val(d.format('yyyy-MM-dd hh:mm:ss'));
        $('.mydatetime').eq(0).datetimepicker().trigger({
            type: 'changeDate',
            date: d
        })
    }
    _ue.ready(function() {
        if(data.content){
            _ue.setContent(data.content);
        }
    });
}
function categoryInit(k) {
    $("#category").empty();
    $.each(news_category,function (key,value) {
        if(key==k){
            $("#category").append("<option value='"+key+"' selected>"+value+"</option>")
        }else{
            $("#category").append("<option value='"+key+"'>"+value+"</option>")
        }
    })
}
function typeInit(parentId,k) {
    $("#type").empty();
    $.each(mapping[parentId],function (key,value) {
        if(key==k){
            $("#type").append("<option value='"+key+"' selected>"+value+"</option>")
        }else{
            $("#type").append("<option value='"+key+"'>"+value+"</option>")
        }
    })
}
//建立一個可存取到該file的url
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}
//判断图片是否为空
function isPicBlank(){
    if($('.imghead').attr("src") == emptyImgPath){
        $('#cancel').removeClass('diyCancel');
        $('#hasPic').val("N");
    }else{
        $('#cancel').addClass('diyCancel');
        $('#hasPic').val("Y");
    }
}
//判断是否为头条新闻
function isHeadValidate(){
    var pic = $('.imghead').attr("src");
    if($('#is_head').is(':checked')){
        $('#is_head').val("1");
    }else{
        $('#is_head').val("0");
    }
    if($("#is_head").val()=="1"){
        if($('.imghead').attr("src") == emptyImgPath){
            $alert("头条新闻必须有版图");
            return false;
        }
    }
    return true;
}

function  formValidationInit() {
    $form2({selector:'#main_form'},{
        title:{required:true},category:{required:true},type:{required:true}
    },{title:{required:'标题不能为空'},category:{required:'模块不能为空'},
        type:{required:'类别不能为空'}
    },function () {
        if(!isHeadValidate()){
            return false;
        }
        var id = $('#id').val();
        var hasPic = $('#hasPic').val();
        var title = $('#title').val();
        var isHead = $('#is_head').val();
        var url = $('#url').val();
        var auther = $('#auther').val();
        var summary = $('#summary').val();
        var category = $('#category').val();
        var type = $('#type').val();
        var keywords = $('#keywords').val();
        var releaseTime = $('#releaseTime').data('utc0');
        var content = _ue.getContent();
        //content = content.replace(/"/gm,'~');
        $.ajaxFileUpload({
            url:"api/v1/p/mms/article/update",
            secureuri:false,
            dataType: 'json',
            fileElementId:'top_pic',
            data:  {
                id: id,
                hasPic: hasPic,
                title: title,
                isHead: isHead,
                url: url,
                auther: auther,
                summary: summary,
                category: category,
                type: type,
                keywords: keywords,
                releaseTime: releaseTime,
                content: content
            },
            success: function (result)  //服务器成功响应处理函数
            {
                //TODO 错误提示及跳转
                if(result.code=="200"){
                    window.location.href = "article-list";
                }else{
                    $alert(result.message);
                }
            }
        });
    });
}
